package com.erp.security;

import java.util.Arrays;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.security.core.Authentication;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.web.authentication.rememberme.InvalidCookieException;
import org.springframework.security.web.authentication.rememberme.TokenBasedRememberMeServices;
import org.springframework.util.DigestUtils;

@SuppressWarnings("deprecation")
public class IpTockenServer extends TokenBasedRememberMeServices{
	public static final ThreadLocal<HttpServletRequest> requestHolder  = new ThreadLocal<HttpServletRequest>();

	public  HttpServletRequest getContext() {
		return requestHolder.get();
	}
	public void setContext(HttpServletRequest context){
		requestHolder.set(context);
	}
	protected String getUserIPAddress(HttpServletRequest request){
		return request.getRemoteAddr();
	}
	//设置cooke
	public void onLoginSuccess(HttpServletRequest request,
			HttpServletResponse response, Authentication successful) {
		// TODO Auto-generated method stub
		try {
			setContext(request);
			super.onLoginSuccess(request, response, successful);
		}finally{
			setContext(null);
			
		}
	}
	protected String makeTokenSignature(long tokenExpiry, String username, String password) {
		// TODO Auto-generated method stub
		return DigestUtils.md5DigestAsHex((username+":"+tokenExpiry+":"+password+":"+getKey()+":"+getUserIPAddress(getContext())).getBytes());
	}
	
	protected void setCookie(String[] tokens, int maxAge,
			HttpServletRequest request, HttpServletResponse response) {
		// TODO Auto-generated method stub
		String[] address = Arrays.copyOf(tokens, tokens.length+1);
		address[address.length-1] = this.getUserIPAddress(request);
		super.setCookie(tokens, maxAge, request, response);
	}
	protected UserDetails processAutoLoginCookie(String[] cookietokens,
			HttpServletRequest request, HttpServletResponse response) {
		try{
			setContext(request);
			String ip = cookietokens[cookietokens.length-1];
			System.out.print("过滤器判断开始");
			if(!this.getUserIPAddress(request).equals(ip)){
				throw new InvalidCookieException("cookie 绑定的ip已经占用了");
			}
			return super.processAutoLoginCookie(Arrays.copyOf(cookietokens, cookietokens.length-1), request, response);
		}finally{
			setContext(null);
		}
		
	}
}
